package net.starwifi.duobao.service.impl;



import net.starwifi.duobao.entity.DBProduct;
import net.starwifi.duobao.entity.DBTimes;
import net.starwifi.duobao.entity.Template;
import net.starwifi.duobao.mvc.Order;
import net.starwifi.duobao.service.DBProductService;
import net.starwifi.duobao.service.StaticService;
import net.starwifi.duobao.service.TemplateService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;


import javax.servlet.ServletContext;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Service - 静态化
 * 
 * @author ruoo
 * @version 1.0
 */
@Service
public class StaticServiceImpl implements StaticService, ServletContextAware {

	/** Sitemap最大地址数 */
	private static final Integer SITEMAP_MAX_SIZE = 40000;

	/** servletContext */
	private ServletContext servletContext;

	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	@Autowired
	private TemplateService templateService;

	@Autowired
	DBProductService dbProductService;


	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Transactional(readOnly = true)
	public int build(String templatePath, String staticPath, Map<String, Object> model) {
		Assert.hasText(templatePath);
		Assert.hasText(staticPath);
		FileOutputStream fileOutputStream = null;
		OutputStreamWriter outputStreamWriter = null;
		Writer writer = null;
		try {
			freemarker.template.Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templatePath);
			File staticFile = new File(servletContext.getRealPath(staticPath));
			File staticDirectory = staticFile.getParentFile();
			if (!staticDirectory.exists()) {
				staticDirectory.mkdirs();
			}
			fileOutputStream = new FileOutputStream(staticFile);
			outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
			writer = new BufferedWriter(outputStreamWriter);
			template.process(model, writer);
			writer.flush();
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(writer);
			IOUtils.closeQuietly(outputStreamWriter);
			IOUtils.closeQuietly(fileOutputStream);
		}
		return 0;
	}

	@Transactional(readOnly = true)
	public int build(String templatePath, String staticPath) {
		return build(templatePath, staticPath, null);
	}




    @Transactional(readOnly = true)
    public int buildIndex() {
        Template template = templateService.get("index");
		Map<String, Object> model = new HashMap<String, Object>();
        return build(template.getTemplatePath(), template.getStaticPath(),model);
    }



	@Transactional(readOnly = true)
	public int buildDBIndex(){
		Template template = templateService.get("dbIndex");
		Map<String,Object> model=new HashMap<String, Object>();
		List<Order> orderBy=new ArrayList<Order>();
		orderBy.add(net.starwifi.duobao.mvc.Order.desc("order"));
		List<DBProduct> products=dbProductService.getListData("o.isMarketable=?1", new Object[]{Boolean.TRUE},orderBy);
		model.put("productList",products);
		return build(template.getTemplatePath(), template.getStaticPath(),model);
	}



	@Override
	public int buildDBTimes(DBTimes dbTimes) {
		Template template = templateService.get("dbProduct");
		Map<String,Object> model=new HashMap<String, Object>();
		model.put("dbProduct",dbTimes.getDbProduct());
		model.put("dbTimes",dbTimes);
		String path="/dbs/product-"+dbTimes.getDbProduct().getId()+"-"+dbTimes.getTimesNo()+".html";
		return build(template.getTemplatePath(),path,model);
	}

	@Transactional(readOnly = true)
	public int delete(String staticPath) {
		Assert.hasText(staticPath);
		File staticFile = new File(servletContext.getRealPath(staticPath));
		if (staticFile.exists()) {
			staticFile.delete();
			return 1;
		}
		return 0;
	}


	@Transactional(readOnly = true)
	public int deleteIndex() {
		Template template = templateService.get("index");
		return delete(template.getStaticPath());
	}

}